//
//  QSTabBarView.swift
//  TestSwift
//
//  Created by Song on 2018/11/7.
//  Copyright © 2018 Song. All rights reserved.
//

import UIKit

protocol QSTabBarViewDelegate: class {
    func qs_tabBarView(tabBarView: QSTabBarView, didSelectedItemAt index: Int)
    func qs_tabBarViewDidSelectedCenterItem(tabBarView: QSTabBarView)
}

class QSTabBarView: UIView {
    // MARK: - 属性
    private var itemBtns: Array<TabBarBtn> = Array<TabBarBtn>()
    /// 记录当前选中的index
    private var currentIndex: Int = 0
    /// 代理
    weak var qs_delegate: QSTabBarViewDelegate?
    /// 中间的按钮
    private lazy var centerBtn: UIButton = {
        let btn = UIButton.init()
        btn.backgroundColor = .blue
        btn.setImage(UIImage.init(named: "icon_transfer_flashlight"), for: .normal)
        btn.addTarget(self, action: #selector(self.clickCenterBtn), for: .touchUpInside)
        return btn
    }()
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    /// 便利初始化方法
    ///
    /// - Parameter itemOcunt: 普通的item个数，一般是偶数
    convenience init(itemOcunt: Int) {
        self.init(frame: .zero)
        self.qs_setupSubViews(itemOcunt: itemOcunt)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Event Response
    /// 点击中间的按钮
    @objc private func clickCenterBtn() {
        self.qs_selectCenter()
    }
    
    /// 点击TabBarItem
    @objc private func clickItemBtn(btn: TabBarBtn) {
        self.qs_selectItemBtn(index: btn.tag, isResponseDelegate: true)
    }
    
    // MARK: - Private Methods
    /// 布局
    func qs_setupSubViews(itemOcunt: Int) {
        // 创建item按钮
        if self.itemBtns.isEmpty {
            for i in 0 ..< itemOcunt {
                let itemBtn = TabBarBtn()
                itemBtn.tag = i
                itemBtn.addTarget(self, action: #selector(self.clickItemBtn(btn:)), for: .touchUpInside)
                self.addSubview(itemBtn)
                self.itemBtns.append(itemBtn)
            }
        }
        
        // 中间位置
        let middleItem = itemOcunt / 2
        
        // 中间按钮布局
        self.addSubview(self.centerBtn)
        self.centerBtn.snp.makeConstraints { (make) in
            make.width.height.equalTo(kAdaptedWidth(50.0))
            make.top.equalTo(-10.0)
            make.centerX.equalTo(self)
        }
        
        // 其他按钮布局
        var leftLastItemBtn = TabBarBtn()
        var rightLastItemBtn = TabBarBtn()
        for i in 0 ..< itemOcunt {
            let itemBtn = self.itemBtns[i]
            
            // 中间按钮的右边
            if i >= middleItem {
                itemBtn.snp.makeConstraints { (make) in
                    make.top.bottom.equalTo(0.0)
                    if i == middleItem {
                        make.left.equalTo(self.centerBtn.snp.right).offset(0.0)
                    } else {
                        make.left.equalTo(rightLastItemBtn.snp.right).offset(0.0)
                    }
                    make.width.equalTo(leftLastItemBtn)
                    if i == itemOcunt - 1 {
                        make.right.equalTo(0.0)
                    }
                }
                
                rightLastItemBtn = itemBtn
            } else {    // 中间按钮的左边
                itemBtn.snp.makeConstraints { (make) in
                    make.top.bottom.equalTo(0.0)
                    if i == 0 {
                        make.left.equalTo(0.0)
                    } else {
                        make.left.equalTo(leftLastItemBtn.snp.right).offset(0.0)
                        make.width.equalTo(leftLastItemBtn)
                    }
                    
                    if i == middleItem - 1 {
                        make.right.equalTo(self.centerBtn.snp.left).offset(0.0)
                    }
                }
                
                leftLastItemBtn = itemBtn
            }
        }
    }
    
    /// 设置tabBarBtn
    ///
    /// - Parameters:
    ///   - title: 文字
    ///   - titleColor: 文字颜色
    ///   - selTitleColor: 选中文字颜色
    ///   - img: 图片
    ///   - selImg: 选中图片
    ///   - index: 下标
    func qs_setTabBarBtn(title: String, titleColor: UIColor = .black, selTitleColor: UIColor = .gray, img: String, selImg: String, at index: Int) {
        let btn = self.itemBtns[index]
        btn.setTitle(title, for: .normal)
        btn.setTitleColor(titleColor, for: .normal)
        btn.setTitleColor(selTitleColor, for: .disabled)
        btn.setImage(UIImage.init(named: img), for: .normal)
        btn.setImage(UIImage.init(named: selImg), for: .disabled)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12.0, weight: .light)
    }
    
    /// 选中哪个item
    ///
    /// - Parameters:
    ///   - index: 下标
    ///   - isResponseDelegate: 是否响应代理方法，默认响应
    func qs_selectItemBtn(index: Int, isResponseDelegate: Bool = true) {
        // 先把上次选择的item设置为可用
        let lastItem = self.itemBtns[self.currentIndex]
        lastItem.isEnabled = true
        // 再把这次选择的item设置为不可用
        let item = self.itemBtns[index]
        item.isEnabled = false
        self.currentIndex = index
        
        if isResponseDelegate {
            // 执行代理
            guard let _ = self.qs_delegate?.qs_tabBarView(tabBarView: self, didSelectedItemAt: index) else { return }
        }
    }
    
    /// 选中中间view
    func qs_selectCenter() {
        // 执行代理
        guard let _ = self.qs_delegate?.qs_tabBarViewDidSelectedCenterItem(tabBarView: self) else { return }
    }
    
    /// 设置item的badge
    ///
    /// - Parameters:
    ///   - badge: badge的值
    ///   - isHidden: badge是否隐藏
    ///   - isOnlyRedDot: badge是否只显示一个红点
    ///   - index: item下标
    func qs_itemBadge(_ badge: Int, isHidden: Bool = true, isOnlyRedDot: Bool = true, at index: Int) {
        let item = self.itemBtns[index]
        item.qs_setBadge("\(badge)", isHidden: isHidden, isOnlyRedDot: isOnlyRedDot)
    }
}

fileprivate class TabBarBtn: UIButton {
    /// badgeLab
    lazy var badgeLab: UILabel = {
        let lab = UILabel.init()
        lab.textColor = .white
        lab.font = UIFont.systemFont(ofSize: 11.0, weight: .light)
        lab.backgroundColor = .red
        lab.textAlignment = .center
        lab.isHidden = true
        return lab
    }()
    
    /// 是否badge只是一个红点
    var isOnlyRedDot: Bool = true
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(badgeLab)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 图片居中
        var center = self.imageView?.center
        center?.x = self.frame.size.width / 2.0
        center?.y = (self.imageView?.frame.size.height)! / 2.0 + 5.0
        self.imageView?.center = center!
        
        // 文字居中
        var newFrame = self.titleLabel?.frame
        newFrame?.origin.x = 0.0
        newFrame?.origin.y = (self.imageView?.frame.maxY)! + 2.0
        newFrame?.size.width = self.frame.size.width
        self.titleLabel?.frame = newFrame!
        self.titleLabel?.textAlignment = .center
        
        // badgeLab的位置
        guard let imgFrame = self.imageView?.frame else { return }
        let labX: CGFloat = imgFrame.origin.x + imgFrame.size.width - 12.0
        let labY: CGFloat = imgFrame.origin.y + 2.0
        let labWidth: CGFloat = self.isOnlyRedDot ? 8.0 : (self.qs_obtainWidthWith(text: self.badgeLab.text ?? "", font: self.badgeLab.font) + 8.0)
        let labHeight: CGFloat = self.isOnlyRedDot ? 8.0 : 12.0
        self.badgeLab.layer.cornerRadius = self.isOnlyRedDot ? (8.0 / 2.0) : (12.0 / 2.0)
        self.badgeLab.layer.masksToBounds = true
        self.badgeLab.frame = CGRect.init(x: labX, y: labY, width: labWidth, height: labHeight)
    }
    
    // MARK: - Private Methods
    /// 获取字符串文字的宽度
    ///
    /// - Parameters:
    ///   - font: 字符串
    ///   - font: 字体大小
    ///   - height: 高度，默认为20.0
    /// - Returns: 宽度
    private func qs_obtainWidthWith(text: String, font : UIFont, height : CGFloat = 20.0) -> CGFloat {
        let attributes = [NSAttributedStringKey.font:font] // 设置字体大小
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        
        let rect : CGRect = text.boundingRect(with: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: height), options: option, attributes: attributes, context: nil)
        
        return rect.width
    }
    
    /// 设置badge
    ///
    /// - Parameters:
    ///   - badge: badge的值
    ///   - isHidden: badge是否隐藏
    ///   - isOnlyRedDot: 是否只显示一个红点
    func qs_setBadge(_ badge: String, isHidden: Bool, isOnlyRedDot: Bool) {
        if !isOnlyRedDot {
            self.badgeLab.text = badge
        }
        self.isOnlyRedDot = isOnlyRedDot
        self.badgeLab.isHidden = isHidden
    }
}
